/*
 * @Date: 2020-02-13 16:38:08
 * @名称: 下载工具里的添加下载列表
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-23 00:11:57
 * @FilePath: /bica_acg/lib/tools/Controller/Download/AddDownload.dart
 */

import 'package:dio/dio.dart';
import 'package:pica_acg/DataBaseFunction.dart';
import 'package:pica_acg/GlobalFunction.dart';
import 'package:pica_acg/GlobalSettings.dart';
import 'package:pica_acg/tools/NetWorkController.dart';
import 'package:pica_acg/tools/extends/Json/ComicsInfo/ComicsInfoListJson.dart';

var comicsInfoList = ComicsInfoListJson.fromJson(null);
var downloadNumber = 0; //当前下载到第几章
var downloadImagesNumber = 0; //单线程使用 记录 下载到第几个图片了

class AddDownload {
  /*
   *
   * get请求
   * 
   * url 请求路径
   * 
   * callBack() function 回调
   * 
   * 可选参数
   * 
   * parameter json类型的 扩展参数
   * 
   * ResponseType 请求方式
   * 
   * requestName 请求名 可以使用请求名终止请求
   * 
   */

  static void addDownloadList(
    String bookId,
    Function callBackFunction, {
    int page = 1,
    Map<String, dynamic> parameter,
    ResponseType responseType,
    CancelToken requestName,
  }) async {
    var downloadList = dataBaseSelect(
      "BookDownloadChapterList",
      'BookId = ? and Download = ? and Success = ?',
      [bookId, true, false],
    );
    downloadList.then((list) {
      if (list.length > 0) {
        print('已检索到需要下载的章节');
        playAnalysis(bookId, list, (returnm) {
          callBackFunction(returnm);
        });
      } else {
        print('当前没有下载任务了或下载已完成');
      }
    });
    return;
  }
}

playAnalysis(
  String bookId,
  List chapterId,
  Function callBack, {
  int page = 1,
  Map<String, dynamic> parameter,
}) {
  Map<int, dynamic> callBack1 = Map();
  // dataBaseSelect('BookDownloadChapterImagesList', 'id!=9999999999999', [])
  //     .then((a) {
  //   print(a);
  // });
  // return;
  if ($global_DownloadplayAnalysisMultithreading) {
    print(chapterId.length);
    for (var i = 0; i < chapterId.length; i++) {
      urlGet(bookId, chapterId[i]["ChapterId"], (returnm) {
        callBack1[i] = returnm;
        if (callBack1.length == chapterId.length) {
          callBack(true);
        }
      });
    }
  }
  //!解析要下载的所有链接 存储到数据库
}

urlGet(
  String bookId,
  String chapterId,
  Function callBack, {
  int page = 1,
  int previousPageCount = 0, // 如果有多页 则记录之前一共有多少页
  Map<String, dynamic> parameter,
}) {
  var url = getComicsInfoEpisodes(
        bookId,
        chapterId,
      ) +
      '&page=$page'; //! 官方用法
  if (parameter != null && parameter.isNotEmpty) {
    StringBuffer sb = new StringBuffer("&");
    parameter.forEach((key, value) {
      sb.write("$key" + "=" + "$value" + "&");
    });
    String paramStr = sb.toString();
    paramStr = paramStr.substring(0, paramStr.length - 1);
    url += paramStr;
  }

  NetWorkController.get(
    url,
    (returnm) async {
      comicsInfoList = ComicsInfoListJson.fromJson(returnm);
      if (comicsInfoList.code == "200") {
        for (var imagesListIndex = 0;
            imagesListIndex < comicsInfoList.data.pages.docs.length;
            imagesListIndex++) {
          Docs imagesList = comicsInfoList.data.pages.docs[imagesListIndex];
          dataBaseInsert('BookDownloadChapterImagesList', {
            "BookId": bookId,
            "ChapterId": chapterId,
            "ImagesName": imagesList.media.path,
            "SeverAddress": imagesList.media.fileServer,
            "PictureAliases": imagesList.media.originalName,
            "AllImages": comicsInfoList.data.pages.total,
            "ThisIsImages": imagesListIndex + previousPageCount,
            "IsPath": (imagesList.isPath == 1) ? true : false,
            "DownloadSuccess": false,
          });
        }

        // print(comicsInfoList.data.pages.page);

        if (comicsInfoList.data.pages.pages > comicsInfoList.data.pages.page) {
          urlGet(
            bookId,
            chapterId,
            callBack,
            page: (comicsInfoList.data.pages.page + 1),
            previousPageCount:
                comicsInfoList.data.pages.docs.length + previousPageCount,
          );
        } else {
          callBack(true);
        }
      } else {
        Future.delayed(Duration(seconds: 2), () {
          urlGet(
            bookId,
            chapterId,
            callBack,
            page: page,
          );
        });
      }
    },
    headers: getApiRequestHeadrs("ComicsEpisodes"),
  );
}
